package com.lyon.custom.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.lyon.custom.server.common.util.DiskUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LeeYan9
 * @since 2021-11-30
 */
public class ConfigCacheService {

    private static final ConcurrentHashMap<String, ConfigItem> CACHE_CONFIG = new ConcurrentHashMap<>();

    public static boolean isUptodate(String groupKey, String md5, String ip, String tag) {
        String serverMd5 = getContentMd5(groupKey, ip, tag);
        return StringUtils.equals(md5, serverMd5);
    }

    /**
     * @param groupKey id
     * @param ip       当前id 判断灰度发布
     * @param tag      tag
     * @return
     */
    private static String getContentMd5(String groupKey, String ip, String tag) {
        ConfigItem configItem = CACHE_CONFIG.get(groupKey);
        if (configItem == null) {
            return null;
        }
        // 灰度发布支持..
        return configItem.getBeatIps().contains(ip) ? configItem.getBeatMd5() : configItem.getMd5();
    }

    /**
     * @param groupKey id
     * @param ip       当前id 判断灰度发布
     * @param tag      tag
     * @return
     */
    public static ConfigItem getItem(String groupKey, String ip, String tag) {
        ConfigItem configItem = CACHE_CONFIG.get(groupKey);
        if (configItem == null) {
            return null;
        }
        // 灰度发布支持..
        return configItem;
    }

    @SneakyThrows
    public static String getContent(String tenantId, String group, String dataId) {
        // TODO 灰度发布支持..
        return DiskUtil.getConfig(dataId, group, tenantId);
    }

    public static String getContentType(String tenantId, String group, String dataId) {
        String groupKey = StrUtil.join(";",tenantId,group,dataId);
        ConfigItem configItem = CACHE_CONFIG.get(groupKey);
        return configItem == null ? null : configItem.getType();
    }

    @SneakyThrows
    public static void dump(String dataId, String group, String tenantId, String content, String type) {
        // 持久化磁盘
        DiskUtil.saveToDisk(dataId, group, tenantId, content);
        // 缓存数据
        String groupKey = StrUtil.join(";",tenantId,group,dataId);
        ConfigItem configItem = new ConfigItem();
        configItem.setGroupKey(groupKey);
        configItem.setLastModifyTime(System.currentTimeMillis());
        configItem.setType(type);
        configItem.setMd5(DigestUtil.md5Hex(content));
        CACHE_CONFIG.put(groupKey, configItem);
    }

    @Data
    static
    class ConfigItem {
        private volatile String md5;
        private volatile String beatMd5;
        private volatile String beatIps;
        private volatile String tag;
        private volatile String type;
        private volatile String groupKey;
        private volatile long lastModifyTime;
    }

}
